package com.clhbolg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clhbolg.domain.Talk;
import com.clhbolg.domain.bo.TalkBo;
import com.clhbolg.domain.vo.TalkVo;
import com.clhbolg.enums.CommentTypeEnum;
import com.clhbolg.enums.FilePathEnum;
import com.clhbolg.mapper.CommentMapper;
import com.clhbolg.mapper.TalkMapper;
import com.clhbolg.model.dto.CommentCountDTO;
import com.clhbolg.model.dto.TalkAdminDTO;
import com.clhbolg.model.dto.TalkDTO;
import com.clhbolg.model.vo.request.ConditionVO;
import com.clhbolg.model.vo.request.TalkVO;
import com.clhbolg.service.ITalkService;
import com.clhbolg.strategy.context.UploadStrategyContext;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author cailinhu
 * @date 2023-02-08
 */
@RequiredArgsConstructor
@Service
@DS("slave")
public class TalkServiceImpl implements ITalkService {

    private final TalkMapper baseMapper;

    @Autowired
    private UploadStrategyContext uploadStrategyContext;

    @Resource
    private CommentMapper commentMapper;
    /**
     * 查询【请填写功能名称】
     */
    @Override
    public TalkVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public TableDataInfo<TalkVo> queryPageList(TalkBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Talk> lqw = buildQueryWrapper(bo);
        Page<TalkVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public List<TalkVo> queryList(TalkBo bo) {
        LambdaQueryWrapper<Talk> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Talk> buildQueryWrapper(TalkBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Talk> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, Talk::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), Talk::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getImages()), Talk::getImages, bo.getImages());
        lqw.eq(bo.getIsTop() != null, Talk::getIsTop, bo.getIsTop());
        lqw.eq(bo.getStatus() != null, Talk::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    public Boolean insertByBo(TalkBo bo) {
        Talk add = BeanUtil.toBean(bo, Talk.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     */
    @Override
    public Boolean updateByBo(TalkBo bo) {
        Talk update = BeanUtil.toBean(bo, Talk.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Talk entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除【请填写功能名称】
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<TalkDTO> listTalks(PageQuery pageQuery) {
      Page<TalkDTO> page= baseMapper.findTalks(pageQuery.build());
        List<Integer> talkIds = page.getRecords().stream().map(TalkDTO::getId).collect(Collectors.toList());

        //查询说说下面的回复数量
        List<CommentCountDTO>  countDTOS=  commentMapper.listCommentCountByTypeAndTopicIds(CommentTypeEnum.TALK.getType(),talkIds);
        Map<Integer, Integer> commentMap = countDTOS.stream().collect(Collectors.toMap(CommentCountDTO::getId, CommentCountDTO::getCommentCount));

        page.getRecords().forEach(item->{
            item.setCommentCount(commentMap.get(item.getId()));
            if (Objects.nonNull(item.getImages()))
            item.setImgs(Convert.toList(String.class, JSONUtil.parseArray(item.getImages())));
        });
        return TableDataInfo.build(page);
    }

    @Override
    public void saveOrUpdateTalk(TalkVO talkVO) {
        Talk convert = Convert.convert(Talk.class, talkVO);
        convert.setUserId(LoginHelper.getUserId());
        baseMapper.insert(convert);
    }

    @Override
    public TableDataInfo<TalkAdminDTO> listBackTalks(ConditionVO conditionVO,PageQuery pageQuery) {
        Page<TalkAdminDTO> talkAdminDTOS=baseMapper.listBackTalks(conditionVO,pageQuery.build());
        talkAdminDTOS.getRecords().stream().forEachOrdered(t->{
            JSONArray array = JSONUtil.parseArray(t.getImages());
            t.setImgs(array.toList(String.class));
        });
        return TableDataInfo.build(talkAdminDTOS);
    }

    @Override
    public TalkAdminDTO getBackTalkById(Integer talkId) {
        TalkAdminDTO talkBackDTO = baseMapper.getTalkByIdAdmin(talkId);

        talkBackDTO.setImgs(JSONUtil.parseArray(talkBackDTO.getImages()).toList(String.class));
        return talkBackDTO;
    }

    @Override
    public void deleteTalkById(Integer talkId) {
        Talk talk = baseMapper.selectById(talkId);
        List<String> list = JSONUtil.parseArray(talk.getImages()).toList(String.class);
        //删除图片
        for (String s : list) {
            uploadStrategyContext.executeDeleteStrategy(FilePathEnum.TALK.getPath()+s);
        }
        baseMapper.deleteById(talk);
    }
}
